package com.example.meterialproject.activitys

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Editable
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ImageSpan
import android.util.Log
import androidx.activity.viewModels
import androidx.core.view.contains
import androidx.core.view.forEach
import com.doodle.android.chips.ChipsView
import com.doodle.android.chips.model.Contact
import com.example.meterialproject.base.BaseActivity
import com.example.meterialproject.R
import com.example.meterialproject.bean.ChipBean
import com.example.meterialproject.databinding.ActivityChipEditBinding
import com.example.meterialproject.exts.TAG
import com.example.meterialproject.exts.click
import com.example.meterialproject.exts.toast
import com.example.meterialproject.view_models.ChipEditViewModel
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipDrawable
import com.pchmn.materialchips.ChipsInput
import com.pchmn.materialchips.model.ChipInterface
import java.util.*


/**
 *
 * @ClassName: ChipEditActivity
 * @Author: android 超级兵
 * @CreateDate: 1/11/22$ 9:57 AM$
 * TODO chip and Edit
 */
class ChipEditActivity : BaseActivity<ActivityChipEditBinding>() {

    private val viewModel: ChipEditViewModel by viewModels()

    @SuppressLint("Recycle")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        /*
         * 作者:android 超级兵
         * 创建时间: 1/10/22 8:30 PM
         * TODO
         *  参考链接:https://stackoverflow.com/questions/50574943/how-to-add-chips-from-material-components-library-to-input-field-in-android
         */
        val tempLength = 4
        binding.edit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(
                charSequence: CharSequence,
                start: Int,
                before: Int,
                count: Int
            ) {
            }

            override fun afterTextChanged(editable: Editable) {
                // 如果
                if (editable.length % tempLength == 0 && editable.isNotEmpty()) {
                    val chip: ChipDrawable =
                        ChipDrawable.createFromResource(this@ChipEditActivity, R.xml.item_chip)

                    chip.text = editable.subSequence(editable.length - tempLength, editable.length)
                    chip.setBounds(0, 0, chip.intrinsicWidth, chip.intrinsicHeight)

                    // 流逝布局
                    val span = ImageSpan(chip)

                    editable.setSpan(
                        span,
                        editable.length - tempLength,
                        editable.length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                }
            }
        })

        binding.btPrintEdit.click {
            binding.btPrintEdit.text = binding.edit.text.toString()
        }

        /*
         * 作者:android 超级兵
         * 创建时间: 1/11/22 10:56 AM
         * TODO 参考链接:https://github.com/pchmn/MaterialChipsInput
         * 设置数据
         */
        binding.chipsInput.filterableList = viewModel.getDataList(this)

        /*
         * 作者:android 超级兵
         * 创建时间: 1/11/22 11:08 AM
         * TODO 输入监听
         */
        binding.chipsInput.addChipsListener(object : ChipsInput.ChipsListener {
            override fun onChipAdded(chip: ChipInterface, newSize: Int) {
                Log.e(TAG, "chip added, $newSize")
            }

            override fun onChipRemoved(chip: ChipInterface?, newSize: Int) {
                Log.e(TAG, "chip removed, $newSize")
            }

            override fun onTextChanged(text: CharSequence?) {
                // 输入监听
                Log.e(TAG, "chip text changed: " + text.toString())
            }
        })

        /*
         * 作者:android 超级兵
         * 创建时间: 1/11/22 3:59 PM
         * TODO 输出结果..
         */
        binding.printButton.click {
            binding.printButton.text = binding.chipsInput.selectedChipList.filter {
                it is ChipBean
            }.map {
                it as ChipBean
            }.toList().toString()

            binding.chipsInput.editText.text toast this
        }


        /*
         * 作者:android 超级兵
         * 创建时间: 1/11/22 4:39 PM
         * TODO 添加chip
         */
        resources.getStringArray(R.array.chips_item1).forEach {
            val chip =
                layoutInflater.inflate(R.layout.item_chip, binding.chipGroup, false) as Chip

            chip.apply {
                text = it
                // 设置右侧删除按钮
                isCloseIconVisible = true

                // 删除监听
                chip.setOnCloseIconClickListener {
                    "已删除:${chip.text}" toast this@ChipEditActivity
                    binding.chipGroup.removeView(
                        chip
                    )
                }

                // 添加chip
                binding.chipGroup.addView(this)
            }
        }

        /*
         * 作者:android 超级兵
         * 创建时间: 1/11/22 4:38 PM
         * TODO chip点击监听
         */
        // 循环group设置child点击事件监听等。。
        binding.chipGroup.forEach { childView ->
            // 必须是chip
            if (childView is Chip) {

                // 点击监听
                childView.setOnClickListener {
                    "${childView.text}-${childView.isChecked}" toast this

                    // chip是为选中状态
                    if (childView.isChecked) {
                        binding.chipsView.addChip(
                            childView.text.toString(), null,
                            Contact(
                                childView.text.toString(),
                                "???",
                                null // Uri.parse("https://robohash.org/1073380367")
                            ),
                            false
                        )
                    } else {
                        val alike = isAlike(binding.chipsView, childView.text.toString())
                        if (alike.first != -1 && binding.chipsView.chips.contains(alike.second)) {
                            // 未选中状态
                            binding.chipsView.removeChipBy(alike.second?.contact)
                        }
                    }
                }

                // 关闭监听
                childView.setOnCloseIconClickListener { closeValue ->
                    if (binding.chipGroup.contains(closeValue)) {
                        if (closeValue is Chip && closeValue.isChecked) {

                            val alike = isAlike(binding.chipsView, closeValue.text.toString())
                            if (alike.first != -1 && binding.chipsView.chips.contains(alike.second)) {
                                // 删除chipsView 元素
                                val removeChipBy =
                                    binding.chipsView.removeChipBy(alike.second?.contact)
                                Log.i(TAG, "删除的为..${closeValue.text}${removeChipBy}")
                                // 状态取反
                                closeValue.isChecked = !closeValue.isChecked
                            }

                        } else {
                            // 删除 chipGroup 中的当前元素
                            binding.chipGroup.removeView(closeValue)
                        }
                    }
                }
            }
        }

        /*
         * 作者:android 超级兵
         * 创建时间: 1/11/22 4:46 PM
         * TODO  chipsView监听
         *  chipsView 官方文档:https://github.com/DoodleScheduling/android-material-chips
         */
        binding.chipsView.setChipsListener(object : ChipsView.ChipsListener {
            override fun onChipAdded(chip: ChipsView.Chip?) {
                // 添加监听【只针对 addChip()】
                Log.i(TAG, "onChipAdded:${chip.toString()}")
            }

            override fun onChipDeleted(chip: ChipsView.Chip) {
                // 删除监听【只针对 addChip()】
                Log.i(TAG, "onChipDeleted:$chip")
                binding.chipGroup.forEach {
                    if (it is Chip) {
                        // 如果文字相同 并且 当前为选中
                        if (chip.contact.emailAddress == it.text && it.isChecked) {
                            // 则改为不选中
                            it.isChecked = !it.isChecked
                        }
                    }
                }
            }

            override fun onTextChanged(text: CharSequence?) {
                // 输入监听【删除也会监听到】
                Log.i(TAG, "onTextChanged:${text}")
//                binding.chipsView.addChip()
            }

            override fun onInputNotRecognized(text: String?): Boolean {
                Log.i(TAG, "onInputNotRecognized:${text}")
                return false
            }
        })



        binding.chipsView.setChipsValidator(object : ChipsView.ChipValidator() {
            override fun isValid(contact: Contact?): Boolean {
                Log.i(TAG, "isValid:${contact}")
                return true
            }
        })
    }


    /*
     * 作者:android 超级兵
     * 创建时间: 1/12/22 10:28 AM
     *  toCompared 待比较的字符串
     */
    private fun isAlike(chipsView: ChipsView, toCompared: String): Pair<Int, ChipsView.Chip?> {
        chipsView.chips.forEachIndexed { index, value ->
            if (value.contact.emailAddress == toCompared) {
                return Pair(index, value)
            }
        }
        return Pair(-1, null)
    }
}